<?php

/**
* alltosun.com 优惠券控制器 index.php
* ============================================================================
* 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 吴松键 (wusj@alltosun.com) $
* $Date: 2014-8-25 上午9:47:33 $
* $Id$
*/

class Action
{
    private $per_page = 20;
    /**
     * 显示优惠券列表
     */
    public function index()
    {
        $page          = Request::Get('page_no', 1);
        $status        = Request::Get('status', 1);
        $is_advenced   = Request::getParam('is_advenced', 0);
        $search_filter = Request::getParam('search_filter', array());

        // 拼装搜索条件
        $filter = array();
        if (isset($search_filter['title']) && $search_filter['title']) {
            $filter['`title` LIKE '] = '%'.$search_filter['title'].'%';
        }
        if (isset($search_filter['offer_price']) && $search_filter['offer_price']) {
            $filter['offer_price'] = $search_filter['offer_price'];
        }
        $filter['status'] = $status;

        $coupon_list = array();
        $coupon_count = _model('coupon')->getTotal($filter);
        if ($coupon_count) {
            $pager = new Pager($this->per_page);
            if ($pager->generate($coupon_count)) {
                Response::assign('pager', $pager);
            }

            $coupon_list = _model('coupon')->getList($filter, ' ORDER BY `id` DESC '.$pager->getLimit($page));
            foreach ($coupon_list as $k=>$v) {
                $coupon_total   = _model('coupon_relation')->getTotal(array('coupon_id'=>$v['id']));
                $receive_coupon = _model('coupon_relation')->getTotal(array('coupon_id'=>$v['id'], '`status` >='=>2));
                $used_coupon    = _model('coupon_relation')->getTotal(array('coupon_id'=>$v['id'], 'status'=>3));
                $coupon_list[$k]['total']   = $coupon_total;
                $coupon_list[$k]['receive'] = $receive_coupon;
                $coupon_list[$k]['used']    = $used_coupon;
            }
        }

        Response::assign('coupon_list', $coupon_list);
        Response::assign('status', $status);
        Response::assign('search_filter', $search_filter);
        Response::assign('is_advenced', $is_advenced);

        Response::display('admin/coupon_list.html');
    }

    //zhangyh 选择添加优惠卷方式
    public function options_add()
    {
        Response::display('admin/options_add.html');
    }

    public function coupon_details()
    {
        $id            = Request::Get('id', 0);
        $page          = Request::Get('page_no', 1);
        $status        = Request::Get('status', 1);
        $is_advenced   = Request::getParam('is_advenced', 0);
        $search_filter = Request::getParam('search_filter', array());

        // 拼装搜索条件
        $is_empty = 0;
        $filter = array();
        if (isset($search_filter['coupon_code']) && $search_filter['coupon_code']) {
            $filter['`coupon_code` LIKE'] = '%'.$search_filter['coupon_code'].'%';
        }
        if (isset($search_filter['user_name']) && $search_filter['user_name']) {
            $user_ids = user_helper::get_user_ids_by_name($search_filter['user_name']);
            if ($user_ids) {
                $filter['user_id'] = $user_ids;
            } else {
                $is_empty = 1;
            }
        }
        if ($status != 1) {
            $filter['status'] = $status;
        }
        $filter['coupon_id'] = $id;

        $coupon_relation_list = array();
        $coupon_info          = array();
        if ($id) {
            $coupon_info = _uri('coupon', $id);
            $coupon_info['is_valid'] = coupon_helper::get_is_valid($id);

            if (!$is_empty) {
                $coupon_relation_count = _model('coupon_relation')->getTotal($filter);
                if ($coupon_relation_count) {
                    $pager = new Pager($this->per_page);
                    if ($pager->generate($coupon_relation_count)) {
                        Response::assign('pager', $pager);
                    }

                    $coupon_relation_list = _model('coupon_relation')->getList($filter, ' ORDER BY `id` DESC '.$pager->getLimit($page));
                }
            }
        }
        Response::assign('coupon_relation_count', $coupon_relation_count);
        Response::assign('coupon_info', $coupon_info);
        Response::assign('coupon_details_list', $coupon_relation_list);
        Response::assign('status', $status);
        Response::assign('id', $id);
        Response::assign('search_filter', $search_filter);
        Response::assign('is_advenced', $is_advenced);

        Response::display('admin/coupon_details.html');
    }

    /**
     * 添加优惠券
     */
    public function add()
    {
        $options_type = Request::Get('options_type', 0);
        if(!$options_type) {
            return '请先选择优惠卷添加的方式';
        }
        $goods_list = _model('goods')->getList(array('1'=>'1'));
        Response::assign('goods_list', $goods_list);
        Response::assign('options_type', $options_type);
        Response::display('admin/add.html');
    }

    /**
     * 编辑优惠券
     */
    public function edit()
    {
        $id = Request::getParam('id', 0);
        $options_type = Request::Get('options_type', 0);
        if(!$options_type) {
            return '参数不对';
        }
        if ($id) {
            $coupon_info = _uri('coupon', $id);
            $coupon_info['total'] = _model('coupon_relation')->getTotal(array('coupon_id'=>$coupon_info['id']));

            Response::assign('coupon_info', $coupon_info);
            Response::assign('id', $id);
        }
        
        $category_info = _uri('category', $coupon_info['category_id']);
        $goods_list = _model('goods')->getList(array('1'=>'1'));
        Response::assign('category_info', $category_info);
        
        Response::assign('goods_list', $goods_list);
        Response::assign('options_type', $options_type);
        Response::display('admin/add.html');
    }

    /**
     * 保存
     */
    public function save()
    {
        $info = Request::getParam('info', array());
        $id   = Request::getParam('id', 0);

        foreach ($info as $k=>$v) {
            if (!is_numeric($v)) {
                $info[$k] = trim(AnFilter::filter_string($v));
            }
        }
        // $info['start_time'] .= ' 00:00:00';
        // $info['end_time']   .= ' 23:59:59';

        if (!isset($info['title']) || !$info['title']) {
            return '请填写优惠券标题';
        }

        if ($info['total']) {
            $coupon_total = $info['total'];
            unset($info['total']);
        }

        if ($id) {
            $coupon_info = _uri('coupon', $id);
            if (!$coupon_info) {
                return '该内容不存在';
            }
            $coupon_relation_info['limit_price'] =  $info['limit_price'];
            $coupon_relation_info['offer_price'] =  $info['offer_price'];

            _model('coupon_relation')->update(array('coupon_id'=>$id), $coupon_relation_info);
            _model('coupon')->update($id, $info);
        } else {
            $coupon_id = _model('coupon')->create($info);

            $coupon_relation_info['coupon_id'] = $coupon_id;
            $coupon_relation_info['limit_price'] =  $info['limit_price'];
            $coupon_relation_info['offer_price'] =  $info['offer_price'];
            $prefix = 'NBD'.time().$info['offer_price'];
            // for ($i=0; $i<$coupon_total; $i++) {
            //     $coupon_relation_info['coupon_code'] = $prefix.mt_rand(100000,999999);
            //     _model('coupon_relation')->create($coupon_relation_info);
            // }
            
            //add 生成6位的
            $for_num = 0;
            for ($i=0; $i<$coupon_total*100; $i++) {
                $rand_code = user_helper::random_hash(6);
                $is_coupon_info = _uri('coupon_relation', array('coupon_code'=>$rand_code));
                if(!$is_coupon_info) {
                    $coupon_relation_info['coupon_code'] = $rand_code;
                    _model('coupon_relation')->create($coupon_relation_info);
                    $for_num++;
                }
                if($for_num == $coupon_total) {
                    break;
                }
            }
        }

        Response::redirect(AnUrl('coupon/admin'));
    }

    /**
     * 删除
     * @return array
     */
    public function delete()
    {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k=>$v) {
            if (!$v) {
                continue;
            }

            $coupon_info = _uri('coupon', (int)$v);
            if (!$coupon_info) {
                continue;
            }

            if (1 == $coupon_info['status']) {
                _model('coupon')->update($v, array('status'=>0));
            } else {
                _model('coupon')->delete($v);
            }
        }

        return 'ok';
    }

    /**
     * 更新状态
     * @return array
     */
    public function change_status()
    {
        $id     = Request::getParam('id', 0);
        $status = Request::getParam('status', 1);
        if (!$id) {
            return '请选择要更改的内容';
        }

        $coupon_info = _uri('coupon', $id);
        if ($status == $coupon_info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        if (1 == $status) {
            _model('coupon')->update($id, array('status'=>1));
        }

        return 'ok';
    }

    public function download_list()
    {
        $id = Request::Get('id', '');
        $page          = Request::Get('page_no', 1);

        $coupon_info = _uri('coupon', $id);
        $filter = array(
                'coupon_id' => $id
            );
        $coupon_relation_count = _model('coupon_relation')->getTotal($filter);
        if ($coupon_relation_count) {
            $pager = new Pager(coupon_config::$excel_num_page);

            $coupon_list = _model('coupon_relation')->getList($filter, ' ORDER BY `id` DESC '.$pager->getLimit($page));
        }

        //使用范围
        if($coupon_info['goods_id']) {
            $goods_info = _uri('goods', $coupon_info['goods_id']);
            $use_scope = $goods_info['title'];
        } else {
            $category_info = _uri('category', $coupon_info['category_id']);
            $use_scope = $category_info['title'];
        }
        if($coupon_info['is_all_user']) {
            $use_num = '多次';
        } else {
            $use_num = '一次';
        }
        foreach($coupon_list as $k=>$v) {
            $coupon_list[$k]['title'] = $coupon_info['title'];
            $coupon_list[$k]['offer_price'] = $coupon_info['offer_price'];
            $coupon_list[$k]['start_time']  = $coupon_info['start_time'];
            $coupon_list[$k]['end_time']    = $coupon_info['end_time'];
            $coupon_list[$k]['use_scope']   = $use_scope;
            $coupon_list[$k]['use_num']     = $use_num;
        }
        $this->export_excel($coupon_list, $coupon_info['title'].'第'.$page.'页');
    }

    /**
     * 优惠券导出
     */
    public function export_excel($list = array(), $coupon_title)
    {
        //初始化excel对象
        $objPHPExcel = new PHPExcel();
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        //设置当前的sheet索引，用于后续的内容操纵
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();
        // 哪几列
        $col_arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G');
        // 第一排的标题
        $col_title_arr = array('优惠码编号', '状态', '标题', '优惠价格', '有效期', '使用范围', '可用次数');
        // 设置文档属性
        foreach ($col_arr as $k => $v) {
            //设置4个列的宽度
            if (in_array($v, array('A','B','C','E'))) {
                $objActSheet->getColumnDimension($v)->setWidth(40);
            } else {
                $objActSheet->getColumnDimension($v)->setWidth(20);
            }
            //设置单位格内容A1,B1,C1,D1
            $objActSheet->setCellValue($v."1", $col_title_arr[$k]);
            //格式化数字为字符串，避免导致数字默认右对齐单元格
            $objActSheet->getStyle($v)->getNumberFormat()->setFormatCode("@");
            //设置自动换行
            $objActSheet->getStyle($v)->getAlignment()->setWrapText(true);
        }

        foreach ($list as $k=>$v) {
            if($v['status'] == '1') {
                $status = '可用';
            } elseif($v['status'] == '2') {
                $status = '已领取';
            } else {
                $status = '已使用';
            }
            $objActSheet->setCellValue('A'.($k+2), $v['coupon_code']);
            $objActSheet->setCellValue('B'.($k+2), $status);
            $objActSheet->setCellValue('C'.($k+2), $v['title']);
            $objActSheet->setCellValue('D'.($k+2), $v['offer_price']);
            $objActSheet->setCellValue('E'.($k+2), $v['start_time'].'--'.$v['end_time']);
            $objActSheet->setCellValue('F'.($k+2), $v['use_scope']);
            $objActSheet->setCellValue('G'.($k+2), $v['use_num']);
        }

        //设置页面类型
        header("Content-Type: application/vnd.ms-excel");
        //用于下载的文件头
        header("Content-Type: application/force-download");
        header("Content-Type: application/download");
        header("Content-Type: application/octet-stream");

        //$title = trim($catebirthday_gift_recordry_name."表").".xls";
        $title = date('Y-m-d').$coupon_title."优惠码.xls";
        // ff正常，ie不正常，下面是从网站找到的解决方案
        if (preg_match('/MSIE/',$_SERVER['HTTP_USER_AGENT'])) {
            $title = rawurlencode($title);
        }
        header("Content-Disposition: attachment; filename=".$title);
        header("Content-Transfer-Encoding: binary");
        //最后修改时间
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        //不使用缓存
        header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: public');
        header("Expires: 0");
        header("Pragma: public");
        $objWriter->save('php://output');
        exit;
    }
}
?>